package cn.ug.pay.mq;

import cn.ug.core.ensure.Ensure;
import cn.ug.pay.bean.WithdrawAuditBean;
import cn.ug.pay.bean.WithdrawBean;
import cn.ug.pay.service.TradeService;
import cn.ug.pay.service.WithdrawService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static cn.ug.config.QueueName.QUEUE_PAY_WITHDRAW;
import static cn.ug.config.QueueName.QUEUE_PAY_WITHDRAW_STATUS;
import static cn.ug.util.RedisConstantUtil.ESIGN_ERROR_KEY;
import static cn.ug.util.RedisConstantUtil.WITHDRAW_STATUS_ERROR_KEY;

/**
 * 提现处理
 * @author ywl
 */
@Component
@RabbitListener(queues = QUEUE_PAY_WITHDRAW)
public class WithdrawStatusReceiver {
    private Log log = LogFactory.getLog(WithdrawStatusReceiver.class);
    private ObjectMapper mapper = new ObjectMapper();
    @Resource
    private TradeService tradeService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @RabbitHandler
    public void process(WithdrawMQ o) throws JsonProcessingException {
        log.info("----发起提现申请----"+mapper.writeValueAsString(o));
        String key = WITHDRAW_STATUS_ERROR_KEY + o.getOrderId();
        String value = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(value)) {
            int num = Integer.parseInt(value);
            if (num > 15) {
                return;
            }
        }

        String numValue = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(numValue)) {
            int num = Integer.parseInt(numValue);
            num++;
            redisTemplate.opsForValue().set(key, String.valueOf(num), 3600, TimeUnit.SECONDS);
        } else {
            redisTemplate.opsForValue().set(key, String.valueOf(1), 3600, TimeUnit.SECONDS);
        }

        //验证参数
        Ensure.that(o.getOrderId()).isNull("17000413");
        Ensure.that(o.getMemberId()).isNull("17000311");
        Ensure.that(o.getAmount()).isNull("17000422");
        Ensure.that(o.getBankCardId()).isNull("17000403");
        tradeService.yeePayWithdraw(o);
        log.info("----提现处理完毕---订单号="+o.getOrderId());
    }

}
